package com.sniper.serviceribbon.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.sniper.model.LineShop;
import com.sniper.serviceribbon.hystrix.LineShopCollapseCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author suzhen
 * @create 2018/3/15
 */
@Service
public class LineShopService {

    private static Logger logger = LoggerFactory.getLogger(LineShopService.class);

    @Autowired
    RestTemplate restTemplate;

    /**
     * 不会用
     *
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "getCommandError")
    public LineShop getCommand(String id) {
        logger.debug("getCommand: {}", id);
        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        LineShopCollapseCommand collapseCommand = new LineShopCollapseCommand(this, id);
        Future<LineShop> lineShopFuture = collapseCommand.queue();
        LineShop lineShop = null;
        try {
            lineShop = lineShopFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        context.close();
        return lineShop;
    }

    public LineShop getCommandError(String id) {
        LineShop lineShop = new LineShop();
        lineShop.setId(id);
        lineShop.setTitle("服务不可用");
        return lineShop;
    }


    @HystrixCommand(fallbackMethod = "getError")
    public LineShop get(String id) {
        logger.debug("get: {}", id);
        return restTemplate.getForObject("http://SERVICE-DBA/line-shop/get?id={1}", LineShop.class, id);
    }

    public LineShop getError(String id, Throwable throwable) {
        LineShop lineShop = new LineShop();
        lineShop.setId(id);
        lineShop.setTitle("服务不可用");
        throwable.printStackTrace();
        return lineShop;
    }

    @HystrixCommand(fallbackMethod = "listError")
    public List<LineShop> list(String ids) {
        logger.debug("list: {}", ids);
        ParameterizedTypeReference<List<LineShop>> responseType = new ParameterizedTypeReference<List<LineShop>>() {
        };
        ResponseEntity<List<LineShop>> responseEntity = restTemplate.exchange("http://SERVICE-DBA/line-shop/list?id={1}", HttpMethod.GET, null, responseType, ids);
        return responseEntity.getBody();
    }

    public List<LineShop> listError(String ids) {
        return Collections.emptyList();
    }
}
